#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网络分析仪重连机制使用示例
展示如何使用增强的重连功能
"""

import time
import logging
from network_analyzer_controller import NetworkAnalyzerController, MeasurementSession

# 配置日志显示
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)


def demonstrate_reconnection_features():
    """演示重连功能特性"""
    print("网络分析仪重连机制演示")
    print("=" * 50)
    
    # 创建控制器实例
    controller = NetworkAnalyzerController(
        ip_address="192.168.1.10",  # 请根据实际情况修改
        timeout=10000
    )
    
    try:
        print("\n1. 尝试连接网络分析仪...")
        if controller.connect():
            print("✓ 连接成功")
            
            # 执行一些基本操作
            print("\n2. 执行设备查询...")
            try:
                idn = controller.get_device_info()
                print(f"✓ 设备信息: {idn}")
                
                print("\n3. 配置测量参数...")
                controller.set_frequency_range(5.2e9, 5.8e9)
                controller.set_sweep_points(201)
                print("✓ 配置完成")
                
                # 模拟网络中断后的重连
                print("\n4. 模拟网络中断和重连...")
                print("   注意：这需要手动断开网络来测试")
                
                # 连续执行操作以测试重连机制
                for i in range(5):
                    try:
                        print(f"   第{i+1}次查询...")
                        data = controller.read_trace_data("S21")
                        print(f"   ✓ 获取到 {len(data)} 个数据点")
                        time.sleep(1)
                    except Exception as e:
                        print(f"   ✗ 操作失败: {e}")
                        break
                        
            except Exception as e:
                print(f"✗ 操作失败: {e}")
                
        else:
            print("✗ 连接失败")
            
    except KeyboardInterrupt:
        print("\n用户中断操作")
    finally:
        print("\n5. 断开连接...")
        controller.disconnect()
        print("✓ 连接已关闭")


def demonstrate_measurement_session_with_reconnection():
    """演示带重连机制的测量会话"""
    print("\n" + "=" * 50)
    print("测量会话重连演示")
    print("=" * 50)
    
    controller = NetworkAnalyzerController("192.168.1.10")
    
    if not controller.connect():
        print("无法连接到设备，跳过演示")
        return
    
    try:
        # 创建测量会话
        session = MeasurementSession(
            controller=controller,
            start_freq=5.2e9,
            stop_freq=5.8e9,
            points=201,
            power_level=-10,
            if_bandwidth=1000
        )
        
        print("\n1. 配置测量会话...")
        session.setup_measurement()
        print("✓ 会话配置完成")
        
        print("\n2. 执行单次测量...")
        try:
            result = session.perform_single_measurement()
            print(f"✓ 测量完成，获取 {len(result['frequency'])} 个数据点")
            
            # 检查信号质量
            quality = session.check_signal_quality(result)
            print(f"✓ 信号质量检查结果: {quality}")
            
        except Exception as e:
            print(f"✗ 测量失败: {e}")
            
        print("\n3. 执行连续测量...")
        try:
            measurements = session.perform_continuous_measurement(
                duration=5,  # 5秒
                interval=1   # 每秒一次
            )
            print(f"✓ 连续测量完成，共 {len(measurements)} 组数据")
            
        except Exception as e:
            print(f"✗ 连续测量失败: {e}")
            
    except Exception as e:
        print(f"✗ 会话操作失败: {e}")
    finally:
        controller.disconnect()


def demonstrate_error_recovery():
    """演示错误恢复机制"""
    print("\n" + "=" * 50)
    print("错误恢复演示")
    print("=" * 50)
    
    controller = NetworkAnalyzerController("192.168.1.10")
    
    print("\n1. 测试无效IP地址处理...")
    invalid_controller = NetworkAnalyzerController("255.255.255.255")
    result = invalid_controller.connect()
    print(f"✓ 无效IP测试结果: {'连接失败' if not result else '意外成功'}")
    
    print("\n2. 测试超时配置...")
    timeout_controller = NetworkAnalyzerController(
        ip_address="192.168.1.10",
        timeout=5000  # 5秒超时
    )
    print("✓ 超时配置已设置")
    
    print("\n3. 测试异常处理...")
    try:
        # 模拟未连接状态下的操作
        controller.set_frequency_range(5.2e9, 5.8e9)
    except Exception as e:
        print(f"✓ 异常处理正常: {type(e).__name__}")


def demonstrate_logging_configuration():
    """演示日志配置"""
    print("\n" + "=" * 50)
    print("日志配置演示")
    print("=" * 50)
    
    # 创建不同日志级别的控制器
    
    # 调试级别
    debug_controller = NetworkAnalyzerController("192.168.1.10")
    debug_controller.logger.setLevel(logging.DEBUG)
    
    # 警告级别
    warn_controller = NetworkAnalyzerController("192.168.1.10")
    warn_controller.logger.setLevel(logging.WARNING)
    
    print("✓ 已配置不同日志级别")
    print("  - DEBUG: 显示详细信息")
    print("  - WARNING: 仅显示警告和错误")
    print("  - ERROR: 仅显示错误")


def main():
    """主函数"""
    print("网络分析仪重连机制使用示例")
    print("=" * 60)
    
    # 检查命令行参数
    import sys
    if len(sys.argv) > 1:
        ip_address = sys.argv[1]
        print(f"使用自定义IP地址: {ip_address}")
    else:
        ip_address = "192.168.1.10"
        print("使用默认IP地址: 192.168.1.10")
        print("可以通过命令行参数指定IP地址: python reconnection_example.py <IP地址>")
    
    try:
        # 演示各个功能
        demonstrate_reconnection_features()
        demonstrate_measurement_session_with_reconnection()
        demonstrate_error_recovery()
        demonstrate_logging_configuration()
        
    except KeyboardInterrupt:
        print("\n用户中断操作")
    except Exception as e:
        print(f"\n运行错误: {e}")
    
    print("\n" + "=" * 60)
    print("演示完成")
    print("\n使用提示:")
    print("1. 确保网络分析仪已开机并连接到网络")
    print("2. 根据实际情况修改IP地址")
    print("3. 可以通过断开网络连接来测试重连机制")
    print("4. 查看日志输出了解重连过程的详细信息")


if __name__ == "__main__":
    main()